package com.aiti.lulian.gxmh.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.service.iml.BaseSerivceImpl;
import com.aiti.base.core.exception.BusinessException;
import com.aiti.base.core.page.PageInfo;
import com.aiti.base.core.page.PageResult;
import com.aiti.framework.commons.dictmodel.entity.SysDictData;
import com.aiti.lulian.constant.GxmhConstant;
import com.aiti.lulian.gxmh.dto.*;
import com.aiti.lulian.gxmh.entity.GovArticle;
import com.aiti.lulian.gxmh.excel.GxmhExcelArticleParamDto;
import com.aiti.lulian.gxmh.excel.GxmhExportArticleVo;
import com.aiti.lulian.gxmh.service.GovArticleManageService;
import com.aiti.lulian.gxmh.vo.*;
import com.aiti.lulian.mapper.SysAreaMapper;
import com.aiti.lulian.mapper.gxmh.GovArticleMapper;
import com.aiti.lulian.mapper.gxmh.GxmhSysMapper;
import com.aiti.lulian.utils.BusinessUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * description: 工信门户管理系统
 * auth fcb
 * date 2025-06-18 09:13
 **/
@Service
@Slf4j
public class GovArticleManageServiceImpl extends BaseSerivceImpl<GovArticleMapper, GovArticle> implements GovArticleManageService {

    private static final String HOT_ARTICLE_= "bd20c662de6611ec848100163e06b789";
    private static final String SHAN_DONG_PROVINCE = "F2557678-A421-4E33-9F18-B93FDB3C86DC";

    @Autowired
    private GxmhSysMapper gxmhSysMapper;
    @Autowired
    private SysAreaMapper sysAreaMapper;

    /**
     * 保存政策
     * @param dto
     * @param loginId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveArticle(GxmhArticleParamDto dto, String loginId) {
        if(StrUtil.isBlank(dto.getFormId())) {
            dto.setFormId(GxmhConstant.DEFAULT_FORM_ID);
        }
        SysUserDto sysUserDto = gxmhSysMapper.queryUserInfo(loginId);
        if(sysUserDto == null) {
            throw new BusinessException("用户不存在");
        }
        this.checkParam(dto, sysUserDto.getUsername());
        GovArticle article = new GovArticle();
        article.setBaseId(IdUtil.simpleUUID());
        article.setLevel(dto.getLevel());
        article.setPolicyType(dto.getPolicyType());
        article.setTitle(dto.getTitle());
        if(GxmhConstant.ADMIN_USER_NAME.equals(sysUserDto.getUsername())) {
            article.setCity(dto.getCity());
            article.setCounty(dto.getCounty());
            article.setProvince(dto.getProvince());
            article.setStreet(dto.getStreet());
        }else {
            article.setProvince(sysUserDto.getProvince());
            article.setCity(sysUserDto.getCity());
            article.setCounty(sysUserDto.getRegion());
            article.setStreet(sysUserDto.getStreet());
        }
        article.setBody(dto.getBody());
        article.setSource(dto.getSource());
        article.setArticlePublishTime(DateUtil.parse(dto.getArticlePublishTime() + " 00:00:00", "yyyy-MM-dd HH:mm:ss"));
        if(StrUtil.isNotEmpty(dto.getHotEndTime())) {
            article.setHotEndTime(DateUtil.parse(dto.getHotEndTime() + " 00:00:00", "yyyy-MM-dd HH:mm:ss"));
        }
        article.setBaseCreateBy(loginId);
        article.setBaseCreateTime(new Date());
        article.setBaseUpdateBy(loginId);
        article.setBaseUpdateTime(new Date());
        article.setIsDelete(0);
        article.setClickCount(0);
        article.setArticleType("sys");
        article.setFormId(dto.getFormId());

        this.save(article);
    }

    private void checkParam(GxmhArticleParamDto dto, String loginUsername) {
        if(StrUtil.isBlank(dto.getArticlePublishTime())) {
            throw new BusinessException("发文时间不能为空");
        }
        if(HOT_ARTICLE_.equals(dto.getPolicyType()) && StrUtil.isBlank(dto.getHotEndTime())) {
            throw new BusinessException("请选择热门政策的结束日期");
        }
        if(StrUtil.isBlank(dto.getTitle())) {
            throw new BusinessException("政策标题不能为空");
        }
        if(StrUtil.isBlank(dto.getBody())) {
            throw new BusinessException("政策正文不能为空");
        }
        if(StrUtil.isBlank(dto.getLevel())) {
            throw new BusinessException("发文层级不能为空");
        }
        if(StrUtil.isBlank(dto.getSource())) {
            throw new BusinessException("政策来源不能为空");
        }
        if(StrUtil.isBlank(dto.getPolicyType())) {
            throw new BusinessException("政策类型不能为空");
        }
        // 如果是管理员账号，则省市区县不能为空
        if(GxmhConstant.ADMIN_USER_NAME.equals(loginUsername)) {
            if(StrUtil.isBlank(dto.getProvince())) {
                throw new BusinessException("所属区域不能为空");
            }
            if(StrUtil.isBlank(dto.getCity())) {
                throw new BusinessException("所属区域不能为空");
            }
            if(StrUtil.isBlank(dto.getCounty())) {
                throw new BusinessException("所属区域不能为空");
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateArticle(GxmhArticleParamDto dto, String loginId) {
        SysUserDto sysUserDto = gxmhSysMapper.queryUserInfo(loginId);
        if(sysUserDto == null) {
            throw new BusinessException("用户不存在");
        }
        this.checkParam(dto, sysUserDto.getUsername());
        // 查询更新之前旧的表单id，如果新的表单id和旧的表单id不一致，则判断当前政策是否存在申报数据。若存在申报数据，则不允许修改
        String oldFormId = this.baseMapper.queryOldFormId(dto.getBaseId());
        if(!dto.getFormId().equals(oldFormId)) {
            Integer delcareCount = this.baseMapper.queryDelcareCount(dto.getBaseId());
            if(delcareCount > 0) {
                throw new BusinessException("当前政策已存在申报数据，无法修改政策表单");
            }
        }
        if(!HOT_ARTICLE_.equals(dto.getPolicyType())) {
            dto.setHotEndTime(null);
        }
        if(StrUtil.isEmpty(dto.getProvince())) {
            dto.setProvince(SHAN_DONG_PROVINCE);
        }
        if(StrUtil.isEmpty(dto.getArticlePublishTime())) {
            throw new BusinessException("发文时间不能为空");
        }

        if(GxmhConstant.ADMIN_USER_NAME.equals(sysUserDto.getUsername())) {
            if(StrUtil.isBlank(dto.getStreet())) {
                dto.setStreet(null);
            }
        }else {
            dto.setProvince(sysUserDto.getProvince());
            dto.setCity(sysUserDto.getCity());
            dto.setCounty(sysUserDto.getRegion());
            dto.setStreet(sysUserDto.getStreet());
        }

        this.baseMapper.updateArticle(dto, loginId);
    }

    /**
     * 查询详情
     * @param baseId
     * @return
     */
    @Override
    public GxmhArticleVo queryArticleByBaseId (String baseId) {
        return this.baseMapper.queryArticleByBaseId(baseId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeByBaseIdList(List<String> baseIdList) {
        if(CollectionUtil.isEmpty(baseIdList)) {
            return;
        }
        this.baseMapper.removeByBaseIdList(baseIdList);
        // 删除对应政策的申报
        this.baseMapper.removePolicyDeclareByPolicyIdList(baseIdList);
    }

    @Override
    public PageResult<GxmhArticleVo> queryArticleList(GxmhArticleQueryParamDto queryDto, String loginId) {
        BusinessUtil.checkPageParam(queryDto);
        SysUserDto sysUserDto = gxmhSysMapper.queryUserInfo(loginId);
        if(sysUserDto == null) {
            throw new BusinessException("用户不存在");
        }
        if(!GxmhConstant.ADMIN_USER_NAME.equals(sysUserDto.getUsername())) {
            queryDto.setProvince(sysUserDto.getProvince());
            queryDto.setCity(sysUserDto.getCity());
            queryDto.setCounty(sysUserDto.getRegion());
            queryDto.setStreet(sysUserDto.getStreet());
        }
        // 前端如果传了省市区参数，则按传值筛选。不传则查全部数据
        IPage<GxmhArticleVo> page = new Page<>(queryDto.getPageNum(), queryDto.getPageSize());
        List<GxmhArticleVo> list = this.baseMapper.queryArticleList(page, queryDto);
        PageResult<GxmhArticleVo> pageResult = new PageResult<>(list, new PageInfo(queryDto.getPageNum(), queryDto.getPageSize()), page.getTotal());
        return pageResult;
    }

    @Override
    public List<GxmhExportArticleVo> getAllData(GxmhArticleQueryParamDto queryDto, String loginId) {
        SysUserDto sysUserDto = gxmhSysMapper.queryUserInfo(loginId);
        if(sysUserDto == null) {
            throw new BusinessException("用户不存在");
        }
        if(!GxmhConstant.ADMIN_USER_NAME.equals(sysUserDto.getUsername())) {
            queryDto.setProvince(sysUserDto.getProvince());
            queryDto.setCity(sysUserDto.getCity());
            queryDto.setCounty(sysUserDto.getRegion());
        }
        IPage<GxmhExportArticleVo> page = new Page<>(1, Integer.MAX_VALUE);
        List<GxmhExportArticleVo> dataList = this.baseMapper.queryExportArticleList(page, queryDto);
        for(GxmhExportArticleVo vo: dataList) {
            String body = vo.getBody();
            if(StrUtil.isEmpty( body)) {
                vo.setBody("");
            }else {
                Document parse = Jsoup.parse(body);
                vo.setBody(parse.text());
            }
        }
        return dataList;
    }

    /**
     * 查询用户所在区域
     * @param loginId
     * @return
     */
    public GxmhUserAreaVo queryUserArea(String loginId) {
        SysUserDto sysUserDto = gxmhSysMapper.queryUserInfo(loginId);
        if(sysUserDto == null) {
            throw new BusinessException("用户不存在");
        }
        GxmhUserAreaVo userAreaVo = new GxmhUserAreaVo();
        userAreaVo.setProvince(sysUserDto.getProvince());
        String provinceName = sysAreaMapper.getBaseNameByBaseId(sysUserDto.getProvince());
        userAreaVo.setProvinceName(provinceName);

        userAreaVo.setCity(sysUserDto.getCity());
        String cityName = sysAreaMapper.getBaseNameByBaseId(sysUserDto.getCity());
        userAreaVo.setCityName(cityName);

        userAreaVo.setCounty(sysUserDto.getRegion());
        String countyName = sysAreaMapper.getBaseNameByBaseId(sysUserDto.getRegion());
        userAreaVo.setCountyName(countyName);

        if(StrUtil.isNotEmpty(sysUserDto.getStreet())) {
            userAreaVo.setStreet(sysUserDto.getStreet());
            String streetName = sysAreaMapper.getBaseNameByBaseId(sysUserDto.getStreet());
            userAreaVo.setStreetName(streetName);
        }

        return userAreaVo;
    }

    public List<SysDictData> queryPolicyTypeList() {
        return this.baseMapper.queryPolicyTypeList();
    }


    /**
     * 查询政策申报
     * @param queryDto
     * @param loginId
     * @return
     */
    public PageResult<GxmhPolicyDeclareListItemVo>  queryPolicyDeclareList(GxmhPolicyDeclareQueryDto queryDto, String loginId) {
        BusinessUtil.checkPageParam(queryDto);
        SysUserDto sysUserDto = gxmhSysMapper.queryUserInfo(loginId);
        if(sysUserDto == null) {
            throw new BusinessException("用户不存在");
        }
        // 前端如果传了省市区参数，则按传值筛选。不传则查全部数据
        if(!GxmhConstant.ADMIN_USER_NAME.equals(sysUserDto.getUsername())) {
            queryDto.setProvince(sysUserDto.getProvince());
            queryDto.setCity(sysUserDto.getCity());
            queryDto.setCounty(sysUserDto.getRegion());
            queryDto.setStreet(sysUserDto.getStreet());
        }
        IPage<GxmhPolicyDeclareListItemVo> page = new Page<>(queryDto.getPageNum(), queryDto.getPageSize());
        List<GxmhPolicyDeclareListItemVo> list = this.baseMapper.queryPolicyDeclareList(page, queryDto);
        PageResult<GxmhPolicyDeclareListItemVo> pageResult = new PageResult<>(list, new PageInfo(queryDto.getPageNum(), queryDto.getPageSize()), page.getTotal());
        return pageResult;
    }

    /**
     * 查询某个自定义表单的申报列表
     * @param queryDto
     * @param loginId
     * @return
     */
    @Override
    public PageResult<GxmhFormDeclareVo> queryFormDeclareList(GxmhPolicyDeclareQueryDto queryDto, String loginId) {
        if(StrUtil.isBlank(queryDto.getFormId())) {
            throw new BusinessException("表单标识不能为空");
        }
        BusinessUtil.checkPageParam(queryDto);
        SysUserDto sysUserDto = gxmhSysMapper.queryUserInfo(loginId);
        if(sysUserDto == null) {
            throw new BusinessException("用户不存在");
        }
        // 管理员账号不设置区县
        if(!GxmhConstant.ADMIN_USER_NAME.equals(sysUserDto.getUsername())) {
            queryDto.setProvince(sysUserDto.getProvince());
            queryDto.setCity(sysUserDto.getCity());
            queryDto.setCounty(sysUserDto.getRegion());
            queryDto.setStreet(sysUserDto.getStreet());
        }
        IPage<GxmhFormDeclareVo> page = new Page<>(queryDto.getPageNum(), queryDto.getPageSize());
        List<GxmhFormDeclareVo> gxmhFormDeclareVos = this.baseMapper.queryPolicyDeclareByFromId(page, queryDto);
        PageResult<GxmhFormDeclareVo> pageResult = new PageResult<>(gxmhFormDeclareVos, new PageInfo(queryDto.getPageNum(), queryDto.getPageSize()), page.getTotal());
        return pageResult;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removePolicyDeclareByBaseIdList(List<String> baseIdList) {
        if(CollectionUtil.isEmpty(baseIdList)) {
            return;
        }
        this.baseMapper.removePolicyDeclareByBaseIdList(baseIdList);
    }

    @Override
    public List<GxmhPolicyDeclareListItemVo> getPolicyDeclareList(GxmhPolicyDeclareQueryDto queryDto, String loginId) {
        SysUserDto sysUserDto = gxmhSysMapper.queryUserInfo(loginId);
        if(sysUserDto == null) {
            throw new BusinessException("用户不存在");
        }
        if(!GxmhConstant.ADMIN_USER_NAME.equals(sysUserDto.getUsername())) {
            queryDto.setProvince(sysUserDto.getProvince());
            queryDto.setCity(sysUserDto.getCity());
            queryDto.setCounty(sysUserDto.getRegion());
        }
        IPage<GxmhPolicyDeclareListItemVo> page = new Page<>(1, Integer .MAX_VALUE);
        List<GxmhPolicyDeclareListItemVo> list = this.baseMapper.queryPolicyDeclareList(page, queryDto);
        return list;
    }


}
